package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.*;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VisitorsVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.service.CommentApi;
import com.tanhua.service.MovementApi;
import com.tanhua.service.UserInfoApi;
import com.tanhua.service.VisitorsApi;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author げっしょく
 * @date 2021/10/26
 */
@Service
public class MovementsService {

    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private MovementApi movementApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private CommentApi commentApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 发布动态
     * @param movement
     * @param multipartFile
     */
    public void publishmovement(Movement movement, MultipartFile[] multipartFile) throws IOException {
        if (movement.getTextContent() == null) {
            throw new BusinessException(ErrorResult.contentError());
        }
        //获取用户ID
        Long id = UserHolder.getId();
        List<String> path = new ArrayList<>();
        //上传文件
        for (MultipartFile file : multipartFile) {
            String upload = ossTemplate.upload(file.getOriginalFilename(), file.getInputStream());
            path.add(upload);
        }
        //保存用户id和上传在OSS中的文件URL
        movement.setUserId(id);
        movement.setMedias(path);
        //调用api保存数据
        String movementId = movementApi.publish(movement);
        mqMessageService.sendLogService(UserHolder.getId(), "0201", "movement", movementId);
        mqMessageService.sendAudiService(movementId);

    }

    /**
     * 分页获取指定用户的所以动态
     * @param page 页码
     * @param pagesize 条数
     * @param userId 用户
     * @return
     */
    public PageResult PgaeMovements(Integer page, Integer pagesize, Long userId) {
        UserInfo userInfo = userInfoApi.getUserById(userId);

        PageResult pageResult = movementApi.pageMovements(page, pagesize, userId);
        List<Movement> items = (List<Movement>) pageResult.getItems();
        List<MovementsVo> list = new ArrayList<>();
        if (items == null || items.size() <= 0) {
            return pageResult;
        }
        for (Movement item : items) {
            if (userInfo != null && item != null) {
                MovementsVo movementsVo = MovementsVo.init(userInfo, item);
                list.add(movementsVo);
            }
        }
        pageResult.setItems(list);
        mqMessageService.sendLogService(UserHolder.getId(), "0201", "movement", null);

        return pageResult;
    }

/*    *//**
     * 查询好友动态
     * @param page
     * @param pagesize
     * @return
     *//*
    public PageResult getFriendMovements(Integer page, Integer pagesize) {
        Long id = UserHolder.getId();
        PageResult pageResultFriend = movementApi.getFriend(id);
        List<Friend> items = (List<Friend>) pageResultFriend.getItems();
        if (items == null || items.size() <= 0) {
            return pageResultFriend;
        }
        List<Long> friends = items.stream().map(item -> item.getFriendId()).collect(Collectors.toList());
        Map<Long, UserInfo> map = userInfoApi.getByIds(friends);
//        PageResult pageResult = movementApi.getFriendsMovements(friends, id);
        PageResult pageResult = movementApi.getFriendMovements(id, page, pagesize);
        List<MovementTimeLine> items1 = (List<MovementTimeLine>) pageResult.getItems();
        List<ObjectId> movementIds = items1.stream().map(item -> item.getMovementId()).collect(Collectors.toList());
        if (movementIds == null || movementIds.size() <= 0) {
            return pageResult;
        }
        List<Movement> list = movementApi.getMovements(movementIds);
        if (list == null && list.size() <= 0) {
            return pageResult;
        }
        List<MovementsVo> movementsVos = new ArrayList<>();
        for (Movement movement : list) {
            UserInfo userInfo = map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo movementsVo = MovementsVo.init(userInfo, movement);
                movementsVos.add(movementsVo);
            }
        }
        pageResult.setItems(movementsVos);

        return pageResult;
    }*/

    /**
     * 查询好友动态
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult getFriendMovements(Integer page, Integer pagesize) {
        //获取用户id
        Long id = UserHolder.getId();
        //根据用户id获取到可以查看的动态
        List<MovementTimeLine> list = movementApi.getVisible(id);
        //判断有没有该用户是否有可以看到动态
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //获取的可见的动态id
        List<ObjectId> movementIds = list.stream().map(m -> m.getMovementId()).collect(Collectors.toList());
        //根据可见的动态id获得动态消息
        List<Movement> movements = movementApi.getMovements(movementIds, page, pagesize);
        return getPageResult(page, pagesize, movements);

    }

    //通过Movement的集合获取用户详细信息并封装成PageResult
    private PageResult getPageResult(Integer page, Integer pagesize, List<Movement> movements) {
        if (CollUtil.isEmpty(movements)) {
            return new PageResult();
        }
        //根据发布动态的用户id获取到用户信息
        List<Long> userIds = movements.stream().map(m -> m.getUserId()).collect(Collectors.toList());
        Map map = userInfoApi.getByUserIds(userIds, null);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : movements) {
            UserInfo userInfo = (UserInfo) map.get(movement.getUserId());
            if (userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);

                String key = Constants.MOVEMENTS_INTERACT_KEY + movement.getId().toHexString();
                String likeKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getId();
                if (redisTemplate.opsForHash().hasKey(key, likeKey)) {
                    vo.setHasLiked(1);
                }
                String loveKey = Constants.MOVEMENT_LOVE_HASHKEY + UserHolder.getId();
                if (redisTemplate.opsForHash().hasKey(key, loveKey)) {
                    vo.setHasLoved(1);
                }
                vos.add(vo);
            }
        }
        mqMessageService.sendLogService(UserHolder.getId(), "0201", "movement", null);
        //合并两个信息并返回
        return new PageResult(page, pagesize, 0L, vos);
    }

    //查询大数据推荐的动态
    public PageResult recommend(Integer page, Integer pagesize) {
        //获取用户id
        Long id = UserHolder.getId();
        //先从reids中获取大数据推荐的动态
        String s = (String) redisTemplate.opsForValue().get(Constants.MOVEMENTS_RECOMMEND + id);
        List<Movement> movement = null;
        //判断reids中获取的数据是否存在
        if (StringUtils.isNotEmpty(s)) {
            //存在，用","分割字符串，再转换成ObjectId类型
            String[] split = s.split(",");
            int start = (page - 1) * pagesize;
            if (start < split.length) {
                List<Long> collect = Arrays.stream(split).skip(page).limit(pagesize).map(s1 -> Long.valueOf(s1)).collect(Collectors.toList());
                movement = movementApi.selectMovement(collect);
            }

        }else {
            //不存在，使用随机选取几条数据
            movement = movementApi.randomMovement(pagesize);
        }

        //通过数据去查询对应的用户信息
        return getPageResult(page, pagesize, movement);



    }

    /**
     * 获取单条动态的信息
     * @param id
     * @return
     */
    public MovementsVo getById(String id) {
        //通过动态id去获取动态
        Movement movement = movementApi.getById(new ObjectId(id));
        if (movement == null) {
            return new MovementsVo();
        }
        //通过动态的userId去查询用户详情
        UserInfo userInfo = userInfoApi.getUserById(movement.getUserId());
        if (userInfo == null) {
            return new MovementsVo();
        }
        mqMessageService.sendLogService(UserHolder.getId(), "0201", "movement", movement.getId().toHexString());
        //讲用户详情和动态详情封装起来并返回
        return MovementsVo.init(userInfo, movement);
    }

    //是否点赞和是否喜欢操作
    public Integer like(String Id1, CommentType like, Boolean bool) {
        ObjectId movementId = new ObjectId(Id1);
        //获取用户id
        Long userId = UserHolder.getId();
        //判断用户是否进行点赞或喜欢
        Boolean b = commentApi.getOperation(userId, movementId, like);
        //用户点赞了进行报错处理
        if (like.getType() == 1) {
            if (bool && b) {
                throw new BusinessException(ErrorResult.likeError());
            } else if (!bool && !b) {
                throw new BusinessException(ErrorResult.disLikeError());
            }
        } else if (like.getType() == 3) {
            if (bool && b) {
                throw new BusinessException(ErrorResult.loveError());
            } else if (!bool && !b) {
                throw new BusinessException(ErrorResult.disloveError());
            }
        }
        //未点赞就在MongoDB中表中添加一条数据
        Comment comment = new Comment();
        comment.setUserId(userId);
        comment.setPublishId(movementId);
        if (like.getType() == 1) {
            comment.setCommentType(CommentType.LIKE.getType());
        }else {
            comment.setCommentType(CommentType.LOVE.getType());
        }
        Integer count = null;
        if (bool) {
            //将对动态的操作存入数据库,并互动条数自增1,并返回最新的互动数据
            comment.setCreated(System.currentTimeMillis());
            count = commentApi.save(comment);
            //并把数据添加到redis中
            String key = Constants.MOVEMENTS_INTERACT_KEY + movementId;
            if (like.getType() == 1) {
                redisTemplate.opsForHash().put(key, Constants.MOVEMENT_LIKE_HASHKEY + userId, "1");
                mqMessageService.sendLogService(UserHolder.getId(), "0203", "movement", null);
            }else {
                redisTemplate.opsForHash().put(key, Constants.MOVEMENT_LOVE_HASHKEY + userId, "1");
                mqMessageService.sendLogService(UserHolder.getId(), "0204", "movement", null);
            }
        }else {
            //取消操作:从数据库中删除该条数据,并返回最新数据
            count = commentApi.delete(comment);
            //取消操作:从redis中删除对应的点赞数据
            if (like.getType() == 1) {
                redisTemplate.opsForHash().delete(Constants.MOVEMENTS_INTERACT_KEY + movementId, Constants.MOVEMENT_LIKE_HASHKEY + userId);
                mqMessageService.sendLogService(UserHolder.getId(), "0206", "movement", null);
            }else {
                redisTemplate.opsForHash().delete(Constants.MOVEMENTS_INTERACT_KEY + movementId, Constants.MOVEMENT_LOVE_HASHKEY + userId);
                mqMessageService.sendLogService(UserHolder.getId(), "0207", "movement", null);
            }
        }
        return count;
    }


    //谁看过我
    public List<VisitorsVo> visitors() {
        //获取当前用户id
        Long id = UserHolder.getId();

        //上次查看时间
        String key = Constants.VISITORS_USER;
        String hashKey = id.toString();
        String s = (String) redisTemplate.opsForHash().get(key, hashKey);
        //判断有没有上一次范文记录
        Long date = StringUtils.isEmpty(s) ? null : Long.valueOf(s);
        //通过id查找看过我主页的小伙伴
        List<Visitors> visitors = visitorsApi.getWhoLookMe(id, date);

        //判断集合是否为空
        if (CollUtil.isEmpty(visitors)) {
            return new ArrayList<>();
        }
        //取出集合中的用户id
        List<Long> visitorUserId = CollUtil.getFieldValues(visitors, "visitorUserId", Long.class);
        //通过用户id去查出对应的用户详情
        Map<Long, UserInfo> map = userInfoApi.getByUserIds(visitorUserId, null);
        //封装返回
        List<VisitorsVo> vos = new ArrayList<>();
        for (Visitors visitor : visitors) {
            UserInfo userInfo = map.get(visitor.getVisitorUserId());
            if (userInfo != null) {
                VisitorsVo vo = VisitorsVo.init(userInfo, visitor);
                vos.add(vo);
            }
        }
        return vos;
    }
}
